package cn.edu.uibe.gsonandpicasso;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private TextView shopNameView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
        imageView=findViewById( R.id.imageView );
        shopNameView=findViewById( R.id.shopNameView );
        Retrofit retrofit=new Retrofit.Builder()
                          .baseUrl( "http://172.24.10.175:8080/foodService/" )
                           .build();

        RetrofitService service=
                retrofit.create( RetrofitService.class );
        Call<ResponseBody> shopCall=
                service.getShopById( "1" );
        shopCall.enqueue( new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    byte[] bytes = response.body().bytes();
                    String text=new String( bytes );
                    Gson gson=new Gson();
                    Shop shop=gson.fromJson(text,Shop.class);
                    String shopName=shop.getShopname();
                    String pic=shop.getPic();

                    shopNameView.setText(shopName);
                    String picUrl="http://172.24.10.175:8080/foodService//images/shop/chuaicai.jpg";
                    Picasso.get()
                    .load( picUrl )
                    .into(imageView);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Toast.makeText( MainActivity.this,
                            t.getLocalizedMessage(),
                         Toast.LENGTH_SHORT ).show();
            }
        } );
    }
}
